﻿using System;
using System.Data;
using System.Collections.Generic;
using System.Text;
using Portal.Environment;
using Portal.Language;
using Portal.Interface;
using System.Text.RegularExpressions;
using Portal.CMS;


namespace Portal.CDSP
{
    public class FCategoryHomeWP : WebPart
    {
        private const int MaxString = 40;
        public override string WebPartId
        {
            get
            {
                return "WebSite.FCategoryHomeWP";
            }
        }


        public override string WebPartFolder
        {
            get
            {
                return "Portal.CDSP";
            }
        }

        public override string Title
        {
            get
            {
                return GetText("FTitle", "SOYT-Nhóm tin trang chủ");
            }
        }


        public override ViewCls[] Views
        {
            get
            {
                return new ViewCls[]{                    
                    new ViewCls("Left",GetText("Left","Hiển thị bên trái"),1),
                    new ViewCls("RightImg",GetText("RightImg","Liên kết hình ảnh"),1),                    
                   };
            }
        }

        public override string NameSpace
        {
            get
            {
                return "Portal.CDSP";
            }
        }


        public override string ClassName
        {
            get
            {
                return "FGroupNewsHomeWP";
            }
        }


        public override RenderInfoCls ClientRenderWebPartWithInfo(string BelongSite, string TabModuleId, string ViewName, string HasPorlet, LoadParamCls loadParamCls)
        {
            RenderInfoCls oRenderInfoCls = new RenderInfoCls();

            try
            {
                if (ViewName.Equals("Left"))
                {
                    oRenderInfoCls.Content = ClientRenderWebPartLeft(TabModuleId, HasPorlet, ref oRenderInfoCls.ModuleTitle);
                }

                if (ViewName.Equals("RightImg"))
                {
                    oRenderInfoCls.Content = ClientRenderWebPartRightImage(TabModuleId, HasPorlet, ref oRenderInfoCls.ModuleTitle);
                }
                return oRenderInfoCls;
            }
            catch (Exception ex)
            {
                oRenderInfoCls.ErrorMsg = ex.Message.ToString();
                oRenderInfoCls.Error = true;
                return oRenderInfoCls;
            }
        }

        public override DataTable ReadingDataService(string belongSite, string ActiveLanguage, ref string IdField, ref string SubjectField)
        {
            return new FSpecialSubjectBLL().ReadingForServiceGroupNewsItem(belongSite, ActiveLanguage);
        }


        // Ảnh liên kết nhóm tin
        private string ClientRenderWebPartRightImage(string TabModuleId, string HasPorlet, ref string ModuleTitle)
        {
            try
            {
                TabModuleCls TabModuleCls = new TabModuleBLL().CreateModelFromXml(TabModuleId);
                if (TabModuleCls == null) throw new Exception("[" + TabModuleId + "] " + GetText("TabModuleIdNull", "not found!"));
                StringBuilder Html = new StringBuilder();
                DataTable dtItems = new FSpecialSubjectBLL().ReadingGroupForImgLinks(TabModuleCls.Id, TabModuleCls.belongSite);

                string GroupSubject = (string)dtItems.Rows[0]["Subject"];
                string belongSite = TabModuleCls.belongSite;
                string UrlParent = Environments.GetNewsCategoryUrl(belongSite, TabModuleCls.Id, GroupSubject, "_RunTime");
                string GroupNewsId = (string)dtItems.Rows[0]["groupnewsid"];

                Html.Append(Environments.GetExtraStyleSheet(TabModuleCls));
                Html.Append(
                    "<div class=\"rightcolStyle\">"
                    );
                string SmallImage = string.Empty;
                string ImageUrl = string.Empty;
                for (int iIndex = 0; iIndex < dtItems.Rows.Count; iIndex++)
                {
                    SmallImage = dtItems.Rows[iIndex]["GroupNewsItemImage"] != null ? dtItems.Rows[iIndex]["GroupNewsItemImage"].ToString() : string.Empty;
                    bool HasImage = SmallImage.Trim().Length > 0;
                    string GroupNewsItemId = (string)dtItems.Rows[iIndex]["GroupNewsItemId"];
                    string GroupNewsItemName = (string)dtItems.Rows[iIndex][Environments.ActiveLanguage + "GroupNewsItemName"];
                    string Url = Environments.GetNewsCategoryUrl(belongSite, GroupNewsItemId, GroupNewsItemName, "_RunTime");
                    if (HasImage)
                    {

                        ImageUrl = Environments.HttpMediaRoot + "/media/" + Environments.PortalAlias + "/GroupNews/images/" + GroupNewsId + "/" + belongSite + "/" + SmallImage;
                    }
                    else
                    {
                        ImageUrl = "images/no_photo.jpg";
                    }
                    Html.Append("<a href=\"" + Url + "\"><img class = \"linkimg\" src=\"" + ImageUrl + "\" /></a>");

                }
                Html.Append(
                    "</div>" +
                    "<div class=clrfix></div>");
                return Html.ToString();
            }
            catch (Exception ex)
            {
                return "ERROR:" + ex.Message.ToString();
            }
        }


        // Danh mục nhóm tin trang chủ
        private string ClientRenderWebPartLeft(string TabModuleId, string HasPorlet, ref string ModuleTitle)
        {
            StringBuilder Html = new StringBuilder();
            try
            {
                TabModuleCls TabModuleCls = new TabModuleBLL().CreateModelFromXml(TabModuleId);
                if (TabModuleCls == null) throw new Exception("[" + TabModuleId + "] " + GetText("TabModuleIdNull", "not found!"));

                FSpecialSubjectCls FSubjectCls = new FSpecialSubjectBLL().CreateModelItem(TabModuleCls.Id, TabModuleCls.belongSite);
                string GroupSubject = FSubjectCls.GroupNewsItemName;
                string GroupNewsItemId = FSubjectCls.GroupNewsItemId;
                string ParentGroupNewsItemId = FSubjectCls.GroupNewsId;
                string belongSite = TabModuleCls.belongSite;
                string NewsByCategoryUrl = Environments.GetNewsCategoryUrl(belongSite, GroupNewsItemId, GroupSubject, "_RunTime");

                Html.Append(
                 "<div class=\"folder\">			" +
                 "<div class=\"folder-head\">\n" +
                 "	<h2>\n" +
                 "       <span>\n" +
                 "           <span>\n" +
                 "           	<a href=\"" + NewsByCategoryUrl + "\">" + GroupSubject.ToUpper() + "</a>" +
                 "	        </span>\n" +
                 "	    </span>\n" +
                 "	</h2>\n" +
                 "	<ul>\n");

                int TopNews;
                try
                {
                    TopNews = int.Parse(Environment.Environments.GetAppSettings("NumCat"));
                }
                catch { TopNews = 4; }
                DataTable dtNews = new FSpecialSubjectBLL().ReadingNews_ChuyenMuc(ParentGroupNewsItemId, GroupNewsItemId, TopNews, belongSite);
                DataTable dtSubCat = new FSpecialSubjectBLL().ReadingSubCatMenuItems(GroupNewsItemId);

                for (int iSub = 0; iSub < dtSubCat.Rows.Count; iSub++)
                {
                    string subUrl = string.Empty;
                    string SubGroupNewsItemId = (string)dtSubCat.Rows[iSub]["GroupNewsItemId"];
                    string SubGroupNewsItemName = (string)dtSubCat.Rows[iSub][Environments.ActiveLanguage + "GroupNewsItemName"];
                    int IsGroupNews = (int)dtSubCat.Rows[iSub]["IsGroupNews"];

                    if (IsGroupNews == 1)
                        subUrl = Environments.GetNewsCategoryUrl(TabModuleCls.belongSite, SubGroupNewsItemId, SubGroupNewsItemName, "_RunTime");
                    else
                        subUrl = Environments.GetStaticHtmlUrl(TabModuleCls.belongSite, SubGroupNewsItemId, SubGroupNewsItemName);

                    Html.Append("<li><a href=\"" + subUrl + "\">" + SubGroupNewsItemName + "</a></li>\n");
                }

                if (dtNews.Rows.Count == 0)
                {
                    Html.Append(
                        "	</ul>\n" +
                        "	<div class=\"clr\"></div>\n" +
                        "</div>" +
                            "<div class=\"folder-content\">" +
                            "</div>"
                    );
                }
                else
                {
                    if (TopNews > dtNews.Rows.Count)
                    {
                        TopNews = dtNews.Rows.Count;
                    }

                    string Description = string.Empty;
                    string SmallImage = string.Empty;
                    string ImageUrl = string.Empty;

                    int iNews = 0;
                    string ShortId = (string)dtNews.Rows[iNews]["ShortId"];
                    string Title = (string)dtNews.Rows[iNews][Environments.ActiveLanguage + "Subject"];
                    DateTime EntryDate = (DateTime)dtNews.Rows[iNews]["EntryDate"];
                    string Url = Environments.GetNewsUrl(belongSite, ShortId, Title, "_runtime");

                    SmallImage = dtNews.Rows[iNews]["SmallImage"] != null ? dtNews.Rows[iNews]["SmallImage"].ToString() : string.Empty;
                    bool HasImage = SmallImage.Trim().Length > 0;
                    Description = (string)dtNews.Rows[iNews][Environments.ActiveLanguage + "ShortContent"];
                    Description = FormatDesc(Description);
                    Description = Ultility.ClearHTMLTags(Description);
                    if (HasImage == false)
                    {
                        ImageUrl = "images/no_photo.jpg";
                    }
                    else
                    {
                        ImageUrl = Environments.HttpMediaRoot + "/media/" + Environments.PortalAlias + "/news/images/" + belongSite + "/" + SmallImage;
                    }

                    Html.Append(
                    "	</ul>\n" +
                    "	<div class=\"clr\"></div>\n" +
                    "</div>" +
                    "<div class=\"folder-content\">\n" +
                    "			<div class=\"folder-content-left\">\n" +
                    "				<a class=\"bigger-title\" href=\"" + Url + "\">" + Title + "</a>\n" +
                    "				<a href=\"" + Url + "\"><img src=\"" + ImageUrl + "\" /></a>\n" +
                    "				<p class=\"date\">Ngày " + EntryDate.ToString("dd-MM-yyyy") + "</p>\n" +
                    "				<p>\n" +
                                        Description +
                    "				</p>\n" +
                    "			</div>\n" +
                    "	        <div class=\"folder-content-right\">\n" +
                    "               <ul>");

                    for (int iIndexNews = 1; iIndexNews < TopNews; iIndexNews++)
                    {
                        ShortId = (string)dtNews.Rows[iIndexNews]["ShortId"];
                        Title = "";
                        try
                        {
                            Title = (string)dtNews.Rows[iIndexNews][Environments.ActiveLanguage + "Subject"];
                        }
                        catch { }
                        Description = "";
                        try
                        {
                            Description = (string)dtNews.Rows[iIndexNews][Environments.ActiveLanguage + "ShortContent"];
                        }
                        catch { }

                        try
                        {
                            EntryDate = (DateTime)dtNews.Rows[iIndexNews]["EntryDate"];
                        }
                        catch { }

                        Url = Environments.GetNewsUrl(belongSite, ShortId, Title, "_runtime");
                        Description = Ultility.ClearHTMLTags(Description);
                        Html.Append(
                                    "<li>" +
                                    "   <a href=\"" + Url + "\">" + Title + "</a>" +
                                    "</li>");
                    }
                    Html.Append(
                        "   </ul>" +
                        "   </div>" +
                        "       <div class=\"clr\"></div>" +
                        "   </div>");
                }
                Html.Append(
                    "</div>");
            }
            catch (Exception ex)
            {
                Html.Append("ERROR:" + ex.Message);
            }
            return Html.ToString();
        }

        private string FormatDesc(string Description)
        {
            int Count = 0;
            int j = 0;
            Description = Regex.Replace(Description, @"<(.|\n)*?>", string.Empty);
            int Length = Description.Length;
            for (int i = 1; i < Description.Length; i++)
            {
                if (Description[i - 1].ToString().Equals(" ") && !Description[i].ToString().Equals(" "))
                    Count++;
                if (Count <= MaxString)
                {
                    j = i;
                }
            }
            if (Count > MaxString)
            {
                Description = Description.ToString().Remove(j, (Length - j));
                Description = string.Concat(Description, "...");
            }
            return Description;
        }

        [AjaxPro.AjaxMethod()]
        public string ServerSideCallRssChannel(string GroupNewsId, string belongSite, string GroupSubject)
        {
            try
            {
                var RSSChannel = new RSimpleSyndicationBLL().MakeXmlDataForChanel(GroupSubject, "RSS-CDSPNA Website", "http://cdspna.edu.vn", "CDSPNA", "CDSPNA", DateTime.Now, DateTime.Now, GroupNewsId, "xml", belongSite);
                return RSSChannel.Url;

            }
            catch (Exception ex)
            {
                return "ERROR: " + ex.Message;
            }
        }

        public string ShowTooltip(string Tooltip)
        {
            string[] charsToTrim = { "'", "[", "]", "*", "\'", ";", ",", ".", "#", "@", "%", };//!@#$%^&*()+=-[]\';,./{}|\":<>?
            for (int i = 0; i < charsToTrim.Length; i++)
            {
                if (Tooltip.IndexOf(charsToTrim[i]) != -1)
                {
                    Tooltip.Replace(charsToTrim[i], "\"" + charsToTrim[i] + "\"");
                }
            }
            return Tooltip;
        }

        public override bool AllowFrontService
        {
            get
            {
                return true;
            }
        }

        public override void RegAjaxPro(System.Web.UI.Page ActivePage)
        {
            AjaxPro.Utility.RegisterTypeForAjax(typeof(FCategoryHomeWP), ActivePage);
        }

    }
}
